package com.samphanie.security.security.handler;

import com.samphanie.common.utils.ApiResponse;
import com.samphanie.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义返回结果：没有权限访问时
 *
 * @author Dries
 * @email 1451691457@qq.com
 */
@Slf4j
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException {
        log.error("用户未授权操作: {}", ex.getMessage());
        log.error("异常信息: {}", ex.getMessage());
        ApiResponse<?> result = ApiResponse.forbidden();
        ResponseUtil.responseWriter(response,  MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK.value(), result);
    }
}
